﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Diagnostics.Contracts;
using ShredTheLog.Api.DataContracts;
using System.ComponentModel.Composition;
using ShredTheLog.Api;

namespace ShredTheLog.Converters
{
    [ValueConversion(typeof(IEnumerable<Language>), typeof(string))]
    public sealed class LanguagesConverter : ConverterBase, IValueConverter
    {
        [Import]
        private IShredServices ShredServices { get; set; }

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is Language)
                return Convert((Language)value);
            else if (value is Language?)
            {
                var v = (Language?)value;
                return v.HasValue ? Convert(v.Value) : null;
            }
            else if (value is IEnumerable<Language>)
                return Convert((IEnumerable<Language>)value);
            else if (value == null || Object.Equals(value, String.Empty))
            {
                // В некоторых случаях может произойти.
                // Например, происходит при инициализации комбобокса выбора языка интерфейса в настройках программы
                return null;
            }
            else
                throw new NotSupportedException();
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException();
        }

        public string Convert(IEnumerable<Language> languages)
        {
            Contract.Requires(languages != null);
            Contract.Ensures(Contract.Result<string>() != null);

            var languageStrings = languages.Select(v => Convert(v));
            var result = String.Join(", ", languageStrings);
            Contract.Assume(result != null);
            return result;
        }

        public string Convert(Language language)
        {
            Contract.Ensures(!String.IsNullOrWhiteSpace(Contract.Result<string>()));

            Type enumType = language.GetType();
            var key = String.Format("s_{0}_{1}", enumType.Name, Enum.GetName(enumType, language));
            Contract.Assume(!String.IsNullOrWhiteSpace(key));
            var result = ShredServices.GetLocalizedString(key);
            Contract.Assume(!String.IsNullOrWhiteSpace(result));
            return result;
        }

        public static readonly LanguagesConverter Default = new LanguagesConverter();
    }
}
